﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Contract;

namespace Service
{
    class DataUploader : IDataUploader
    {
        public void Upload(MyFile Mf)
        {
            string ServerPath = Path.Combine("Storage", Mf.Name);
            using (FileStream fs = new FileStream(ServerPath, FileMode.Create))
        {
            int bufferSize = 1 * 1024 * 1024; // 1 MB buffer
            byte[] buffer = new byte[bufferSize];
            int bytes;

            while ((bytes = Mf.Value.Read(buffer, 0, bufferSize)) > 0)
            {
                fs.Write(buffer, 0, bytes);
                fs.Flush();
            }
        }
    }


        public Stream Download(string name)
        {
            string fPath = Path.Combine("Storage", name);

            if (!File.Exists(fPath))
                throw new FileNotFoundException("File was not found", Path.GetFileName(fPath));

            return new FileStream(fPath, FileMode.Open, FileAccess.Read);
           // return ReadFully(fs);
        }


        public void Delete(string name)
        {
            string serverPath = Path.Combine("Storage", name);

            if (File.Exists(serverPath))
            {
                File.Delete(serverPath);
            }
            
        }

        public  MyFile[] Getfilesinfo(string filesPath)
        {
            string BasePath = "Storage";
            if (!string.IsNullOrEmpty(filesPath))
                BasePath  = Path.Combine("Storage", filesPath);
            DirectoryInfo dirInfo = new DirectoryInfo(BasePath);
            FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
            
            return (from f in files 
                    select new MyFile()
                    {  
                        Name = f.Name,
                        Size = f.Length,
                        Value = null
                    }).ToArray();
                   
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        
    }

    }

